const Recipe = require('../models/recipe.model');
const ApiError = require('../utils/ApiError');
const { getPagination } = require('../utils/pagination');

/**
 * 食谱服务
 */
class RecipeService {
  /**
   * 获取食谱列表
   * @param {Object} filter 过滤条件
   * @param {Object} options 分页和排序选项
   * @returns {Promise<QueryResult>} 食谱列表和分页信息
   */
  async getRecipes(filter = {}, options = {}) {
    const { page, limit, sortBy } = options;

    // 构建查询条件
    const query = { ...filter, isDeleted: false };

    // 构建排序条件
    const sort = {};
    if (sortBy) {
      const [field, order] = sortBy.split(':');
      sort[field] = order === 'desc' ? -1 : 1;
    } else {
      // 默认按创建时间倒序
      sort.createdAt = -1;
    }

    // 获取分页参数
    const { skip, limit: limitPerPage } = getPagination(page, limit);

    // 执行查询
    const recipes = await Recipe.find(query)
      .populate('category._id', 'name')
      .populate('ingredients.food._id', 'name unit')
      .populate('author._id', 'name username')
      .sort(sort)
      .skip(skip)
      .limit(limitPerPage);

    // 获取总数
    const total = await Recipe.countDocuments(query);

    return {
      results: recipes,
      page,
      limit: limitPerPage,
      totalPages: Math.ceil(total / limitPerPage),
      total,
    };
  }

  /**
   * 创建食谱
   * @param {Object} recipeData 食谱数据
   * @returns {Promise<Recipe>} 创建的食谱
   */
  async createRecipe(recipeData) {
    const recipe = await Recipe.create(recipeData);
    await recipe.populate([
      { path: 'category._id', select: 'name' },
      { path: 'ingredients.food._id', select: 'name unit' },
      { path: 'author._id', select: 'name username' }
    ]);
    return recipe;
  }

  /**
   * 更新食谱
   * @param {string} recipeId 食谱ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<Recipe>} 更新后的食谱
   */
  async updateRecipe(recipeId, updateData) {
    const recipe = await Recipe.findById(recipeId);
    if (!recipe) {
      throw new ApiError(404, '食谱不存在');
    }

    Object.assign(recipe, updateData);
    await recipe.save();
    
    await recipe.populate([
      { path: 'category._id', select: 'name' },
      { path: 'ingredients.food._id', select: 'name unit' },
      { path: 'author._id', select: 'name username' }
    ]);
    
    return recipe;
  }

  /**
   * 获取食谱详情
   * @param {string} recipeId 食谱ID
   * @returns {Promise<Recipe>} 食谱详情
   */
  async getRecipeById(recipeId) {
    const recipe = await Recipe.findOne({ _id: recipeId, isDeleted: false })
      .populate('category._id', 'name')
      .populate('ingredients.food._id', 'name unit')
      .populate('author._id', 'name username');

    if (!recipe) {
      throw new ApiError(404, '食谱不存在');
    }

    // 更新浏览次数
    recipe.viewCount += 1;
    await recipe.save();

    return recipe;
  }

  /**
   * 删除食谱
   * @param {string} recipeId 食谱ID
   * @returns {Promise<void>}
   */
  async deleteRecipe(recipeId) {
    const recipe = await Recipe.findById(recipeId);
    if (!recipe) {
      throw new ApiError(404, '食谱不存在');
    }

    await Recipe.deleteOne({ _id: recipeId });
  }

  /**
   * 软删除食谱（标记为已删除）
   * @param {string} recipeId 食谱ID
   * @returns {Promise<Recipe>} 标记为已删除的食谱
   */
  async softDeleteRecipe(recipeId) {
    const recipe = await Recipe.findById(recipeId);
    if (!recipe) {
      throw new ApiError(404, '食谱不存在');
    }

    // 标记为已删除
    recipe.isDeleted = true;
    recipe.deletedAt = new Date();
    await recipe.save();

    return recipe;
  }

  /**
   * 恢复已删除的食谱
   * @param {string} recipeId 食谱ID
   * @returns {Promise<Recipe>} 恢复的食谱
   */
  async restoreRecipe(recipeId) {
    const recipe = await Recipe.findById(recipeId);
    if (!recipe) {
      throw new ApiError(404, '食谱不存在');
    }

    // 恢复食谱
    recipe.isDeleted = false;
    recipe.deletedAt = null;
    await recipe.save();

    return recipe;
  }
}

module.exports = new RecipeService(); 